package com.zhangyj.db.util;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

//import com.zhangyj.db.DBFactory;

public abstract class BaseDBUtil {

	public int getIntegerId(String tableName, Connection conn) throws SQLException {
		int id = 1;
		try {
			String sql = "select currentId from idinfo where tableName=?";

			//conn = DBFactory.newConnection();
			PreparedStatement ps = conn.prepareStatement(sql);
			ps.setString(1, tableName);
			ResultSet rst = ps.executeQuery();
			boolean has = false;
			if (rst.next()) {
				id = rst.getInt(1);
				has = true;
			}
			rst.close();
			ps.close();
			if (has) {
				sql = "update idinfo set currentId=? where tableName=?";
			} else {
				sql = "insert idinfo (currentId,tableName) values(?,?)";
			}
			ps = conn.prepareStatement(sql);
			ps.setInt(1, id + 1);
			ps.setString(2, tableName);
			ps.execute();
			ps.close();
		} catch (SQLException e) {
			throw e;
		}
		return id;
	}

	void addOrder(StringBuilder builder, String orderField, String orderTable, boolean isDesc) {
		boolean changed = false;
		if (orderTable != null && orderTable.length() > 0) {
			builder.append(" order by ").append(orderTable).append(".");
			changed = true;
		}
		if (orderField != null && orderField.length() > 0) {
			if (changed) {
				builder.append(orderField);
			} else {
				builder.append(" order by ").append(orderField);
			}
			changed = true;
		}
		if (changed) {
			if (isDesc) {
				builder.append(" desc");
			} else {
				builder.append(" asc");
			}
		}
	}

	public abstract String buildPagnationSql(String sql, int pageNo, int size, int tatalCount, String orderField, String orderTable, boolean isDesc);

}
